<template>
  <div class="table_container">
    <div class="table_top_btn">
      <div class="left_btn">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="openAddOrEdit(['receive', 'add'], {})"
          >新增</el-button
        >
      </div>

      <right-toolbar
        @queryTable="queryList"
        :searchConfig="searchConfig"
        :columns.sync="columns"
        @search="handleSearch"
      >
      </right-toolbar>
    </div>

    <div class="table_area">
      <el-table
        height="100%"
        v-loading="loading"
        :data="receiveData"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column   :label="t('tableColumns.operation')"  align="center" fixed width="200">
          <template #default="{ row }">
            <div class="operate_link_btn">
              <el-link type="warning" :underline="false" :icon="ArrowLeft"
                >撤销</el-link
              >
              <el-link type="primary" :underline="false" :icon="Edit"
                >重申</el-link
              >
              <el-link type="danger" :underline="false" :icon="Delete"
                >删除</el-link
              >
            </div>
          </template>
        </el-table-column>
        <template v-for="(item, index) in columns" :key="item.key">
          <el-table-column
            v-if="item.visible"
            :prop="item.prop"
             :label="t(`tableColumns.${item.langKey}`)"
            :width="item.width"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              <div
                v-if="item.prop == 'receiveNo'"
                :style="{
                  color: colors.primaryColor,
                  cursor: item.isclick ? 'pointer' : '',
                }"
                @click="openAddOrEdit(['receive', 'detail'], row)"
              >
                {{ row.receiveNo }}
              </div>

              <el-tag
                v-else-if="item.prop == 'enableFlag'"
                :type="
                  row.enableFlag == 0
                    ? 'danger'
                    : row.enableFlag == 1
                    ? 'warning'
                    : 'success'
                "
                >{{
                  filterStatus(
                    row.enableFlag,
                    'documentStatus',
                    'id',
                    'langKey'
                  ) || '无'
                }}</el-tag
              >
              <span
                v-else-if="
                  item.prop == 'ScheduledReturnDate' ||
                  item.prop == 'receiveDate'
                "
              >
                {{
                  parseTime(row[item.prop], '{y}-{m}-{d} {h}:{i}:{s}') || '无'
                }}
              </span>
              <span v-else>{{ row[item.prop] || '无' }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <div class="pagination-area">
      <pagination
        :total="page.total"
        v-model:page="page.pageNum"
        v-model:limit="page.pageSize"
        @pagination="queryList"
      />
    </div>
    <addOrEdit
      ref="addOrEditDialogRef"
      v-model:add-edit-info="operate"
      @getCanUseAssetsData="queryCanUseAssetsData"
      @submitAddEditInfo="submit"
      @cancelAddEditInfo="cancel"
    ></addOrEdit>
  </div>
</template>

<script setup name="AssetisList">
import colors from '@/assets/styles/variables.module.scss'
import { Edit, ArrowLeft, Delete } from '@element-plus/icons-vue'
import RightToolbar from '@/components/RightToolbar'
import AshMoreToolBar from '@/components/AshMoreToolBar/index'
import addOrEdit from '@/components/AshDialog/addOrEdit.vue'
import { assetsColums, receiveColums } from '@/utils/table/columns'
import {
  getAssetsReceiveList,
  AddAssetsReceive,
  getAssetsReceiveDetail,
  getAssetsCanReceive,
} from '@/api/assetsManage/receiveAndBack'
import { GetOrganizationTreeAll } from '@/api/assetsManage/organization'
import { GetUserInfoAll } from '@/api/sys/user'
import { getUserInfo } from '@/utils/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { provide, reactive, toRaw } from 'vue'
const { proxy } = getCurrentInstance()
import { documentStatus } from '@/utils/statuData'
const { AssetClassification } = proxy.useDict('AssetClassification')

const receiveData = ref([]) //退还列表
const loading = ref(false)
const columns = receiveColums
const page = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 100,
})
const users = ref([])
const organizes = ref([])
const selectedOrganization = ref(null)

const searchConfig = ref({
  form: {},
  formItems: [
    {
      label: '单据状态',
      prop: 'enableFlag',
      type: 'el-select',
      attrs: { placeholder: '请选择单据状态' },
      options: documentStatus,
      optionProps: {
        key: 'id',
        label: 'name',
        value: 'id',
      },
      events: {},
    },

    {
      label: '领用组织',
      prop: 'receiveOrganizationId',
      type: 'el-tree-select',
      attrs: {
        'check-strictly': true, //任意节点都可以选
        clearable: true,
        placeholder: '请选择领用组织',
      },
      options: organizes,
      optionProps: {
        label: 'Label',
        children: 'children',
        value: 'value',
      },
      events: {},
    },
    {
      label: '使用人员',
      prop: 'useUserName',
      type: 'el-input',
      attrs: { placeholder: '请输入使用人员' },
    },
    {
      label: '领用备注',
      prop: 'receiveRemark',
      type: 'el-input',
      attrs: { placeholder: '请输入领用备注' },
    },
  ],
  rules: {},
})

const canUseAssetsInfo = reactive({
  data: [],
  page: {
    total: 0,
    pageNum: 1,
    pageSize: 100,
  },
  loading: false,
  searchInfo: searchConfig,
}) // 传给孙组件的资产数据
provide('canUseAssetsInfo', canUseAssetsInfo)

//组织点击获取人员
const useOrganizationNodeClick = (node) => {
  selectedOrganization.value = node
  operate.formInfo.receiveOrganizationId = selectedOrganization.value.value
  queryAllUsers(operate.formInfo.receiveOrganizationId)
}

const operate = reactive({
  openObj: {
    visible: false,
    openKey: '', //add edit detail
    openType: '', //维修 报废 退还 领用....
    openTitle: '',
    tableTitle: '',
    addLoading: false, //防止重复提交
  },
  formInfo: {},
  formItems: [
    {
      label: '退还日期',
      prop: 'returnDate',
      type: 'el-date-picker',
      span: 12,
      attrs: {
        type: 'date',
        'value-format': 'YYYY-MM-DD',
        'disabled-date': (date) => proxy.dateAfterToday(date, true),
        clearable: true,
        disabled: false,
        placeholder: '请选择退还日期',
      },
      events: {},
      rules: [{ required: true, message: '请选择退还日期', trigger: 'change' }],
    },
    {
      label: '审批人',
      prop: 'returnDate',
      type: 'el-date-picker',
      span: 12,
      attrs: {
        type: 'date',
        'value-format': 'YYYY-MM-DD',
        'disabled-date': (date) => proxy.dateAfterToday(date, true),
        clearable: true,
        disabled: false,
        placeholder: '请选择退还日期',
      },
      events: {},
      rules: [{ required: true, message: '请选择退还日期', trigger: 'change' }],
    },
    {
      label: '退还备注',
      prop: 'receiveRemark',
      type: 'el-input',
      span: 24,
      attrs: {
        clearable: true,
        disabled: false,
        placeholder: '请输入领用备注',
      },
      events: {},
    },
  ],

  loadingUser: false,
  tableData: [], //表格数据，添加的时候为空，其他情况为查询赋值
  toBeDelData: [], //需要移除的数据
})

//1111获取列表
const queryList = () => {
  const params = {
    pagination: page.pageNum - 1,
    pageRow: page.pageSize,
    isInit: true,
    ...searchConfig.value.form,
  }
  loading.value = true
  getAssetsReceiveList(params)
    .then((res) => {
      loading.value = false
      receiveData.value = res.output.output
      page.total = res.output.count
    })
    .catch((err) => {
      loading.value = false
    })
}

//获取人员,必须先选择使用组织
const queryAllUsers = (organizeId) => {
  operate.loadingUser = true
  GetUserInfoAll({
    // orgNo_Default: organizeId,
    subordinateDepartmentId: organizeId,
  })
    .then((res) => {
      users.value = res.output
      operate.loadingUser = false
    })
    .catch((err) => {
      users.value = []
      operate.loadingUser = false
    })
}

//查询单据详情
const queryAssetsDetail = (receiveId) => {
  getAssetsReceiveDetail({ receiveNo: receiveId }).then((res) => {
    operate.tableData = res.output
    console.log('详情', res)
  })
}
//222添加修改相关
const openAddOrEdit = (typeKey, row) => {
  console.log(`打开${typeKey}对话框`)
  const type = typeKey[0]
  const key = typeKey[1]
  const title =
    key == 'add'
      ? '添加领用'
      : key == 'edit'
      ? '编辑资产'
      : key == 'return'
      ? '归还资产'
      : '资产详情'
  operate.openObj = {
    visible: true,
    openKey: key,
    openType: type,
    openTitle: title,
    tableTitle: '领用资产',
    addLoading: false,
  }

  operate.formInfo = {
    ...row,
    // useUserId: Number(row.useUserId) || null,
    useUserId: row.useUserId || null,
  }
  if (key != 'add') {
    queryAssetsDetail(row.receiveNo)
  }
}

//获取组织
const queryOrganization = () => {
  GetOrganizationTreeAll("")
    .then((res) => {
      // organizes.value = [res.output]
      organizes.value = res.output
    })
    .catch((err) => {
      console.log('组织获取失败', err)
    })
}

//添加领用单的提交
const submit = async (info) => {
  operate.openObj.addLoading = true
  const sub = info.infoSub.map((item, index) => {
    return {
      assetsId: item.assetsId,
      assetsName: item.assetsName,
      rowId: index,
    }
  })
  const form = {
    createUserId: JSON.parse(getUserInfo()).userId,
    ...info.info,
  }
  let params = {
    Info: form,
    InfoSub: sub,
  }
  try {
    await AddAssetsReceive(params).then((res) => {
      ElMessage({ message: `领用单据:${res.output}添加成功`, type: 'success' })
    })
    await cancel()
    await queryList()
  } catch (error) {
    operate.openObj.addLoading = false
  }
}
//取消添加
const cancel = () => {
  operate.openObj.visible = false
}

///3333高级搜索的
//确定高级搜索
const handleSearch = async (info) => {
  console.log('高级搜索的信息', info)
  await queryList()
}

//44444444孙组件的列表数据
//获取可领用资产
const queryCanUseAssetsData = () => {
  canUseAssetsInfo.loading = true
  let params = {
    pagination: canUseAssetsInfo.page.pageNum - 1,
    pageRow: canUseAssetsInfo.page.pageSize,
    isInit: true,
    enableFlag: 0,
    ...canUseAssetsInfo.searchInfo.form,
  }
  getAssetsCanReceive(params)
    .then((res) => {
      canUseAssetsInfo.data = res.output.output
      canUseAssetsInfo.page.total = res.output.count
      canUseAssetsInfo.loading = false
    })
    .catch(() => {
      canUseAssetsInfo.data.value = []
      canUseAssetsInfo.loading = false
    })
}

onMounted(() => {
  queryList()
  queryAllUsers('')
  queryOrganization()
})
</script>
<style lang="scss" scoped>
.table_container {
  padding: 0;
}
</style>
